package com.pm.controller;

import com.pm.entity.Project;
import com.pm.entity.User;
import com.pm.service.ProjectService;
import com.pm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目管理控制器
 */
@RestController
@RequestMapping("/api/projects")
@CrossOrigin(origins = "*")
public class ProjectController {
    
    @Autowired
    private ProjectService projectService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取所有项目
     */
    @GetMapping
    public ResponseEntity<List<Project>> getAllProjects() {
        List<Project> projects = projectService.getAllProjects();
        return ResponseEntity.ok(projects);
    }
    
    /**
     * 根据ID获取项目
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getProjectById(@PathVariable String id) {
        try {
            Project project = projectService.findById(id);
            if (project == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "项目不存在");
                return ResponseEntity.badRequest().body(error);
            }
            return ResponseEntity.ok(project);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "获取项目信息失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 创建项目
     */
    @PostMapping
    public ResponseEntity<?> createProject(@RequestBody Project project, Authentication authentication) {
        try {
            // 设置项目管理员为当前用户
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            project.setManagerId(currentUser.getId());
            
            Project createdProject = projectService.createProject(project);
            
            Map<String, Object> response = new HashMap<>();
            response.put("project", createdProject);
            response.put("message", "项目创建成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 更新项目
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateProject(@PathVariable String id, @RequestBody Project project, Authentication authentication) {
        try {
            // 检查权限：只有项目管理员可以更新项目
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Project existingProject = projectService.findById(id);
            
            if (existingProject == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "项目不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (!existingProject.getManagerId().equals(currentUser.getId())) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限修改此项目");
                return ResponseEntity.badRequest().body(error);
            }
            
            project.setId(id);
            project.setManagerId(existingProject.getManagerId()); // 保持原管理员
            Project updatedProject = projectService.updateProject(project);
            
            Map<String, Object> response = new HashMap<>();
            response.put("project", updatedProject);
            response.put("message", "项目更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 删除项目
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteProject(@PathVariable String id, Authentication authentication) {
        try {
            // 检查权限：只有项目管理员可以删除项目
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Project existingProject = projectService.findById(id);
            
            if (existingProject == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "项目不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (!existingProject.getManagerId().equals(currentUser.getId())) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限删除此项目");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean deleted = projectService.deleteProject(id);
            if (!deleted) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "删除项目失败");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "项目删除成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "删除项目失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 获取我管理的项目
     */
    @GetMapping("/my-managed")
    public ResponseEntity<List<Project>> getMyManagedProjects(Authentication authentication) {
        String currentUsername = authentication.getName();
        User currentUser = userService.findByUsername(currentUsername);
        List<Project> projects = projectService.findByManagerId(currentUser.getId());
        return ResponseEntity.ok(projects);
    }
    
    /**
     * 根据状态获取项目
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<Project>> getProjectsByStatus(@PathVariable String status) {
        List<Project> projects = projectService.findByStatus(status);
        return ResponseEntity.ok(projects);
    }
    
    /**
     * 更新项目状态
     */
    @PatchMapping("/{id}/status")
    public ResponseEntity<?> updateProjectStatus(@PathVariable String id, @RequestBody Map<String, String> request, Authentication authentication) {
        try {
            // 检查权限：只有项目管理员可以更新项目状态
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Project existingProject = projectService.findById(id);
            
            if (existingProject == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "项目不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (!existingProject.getManagerId().equals(currentUser.getId())) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限修改此项目状态");
                return ResponseEntity.badRequest().body(error);
            }
            
            String status = request.get("status");
            boolean updated = projectService.updateProjectStatus(id, status);
            
            if (!updated) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "更新项目状态失败");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "项目状态更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}